package controller;

import Data.File;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import util.UpdateAbsolutePath;
import util.UpdatePieChart;

import java.io.IOException;

import static controller.MainController.*;
import static util.FileRW.writeDisk;


public class FileController {

    @FXML
    private AnchorPane archorPane;

    @FXML
    private TextArea contentField;

    @FXML
    private Button saveItem;

    @FXML
    private ToolBar toolBar;

    @FXML
    private Text fileName;

    private static PieChart diskChart;

    @FXML
    void initialize() {
        fileName.setText(currentFile.getFileName());
        contentField.setText(currentFile.getContent());
        if (currentFile.isReadOnly()) {
            contentField.setDisable(true);
            //   contentField.setEditable(false);
        }
    }

    @FXML
    void saveContent(ActionEvent event) throws IOException, ClassNotFoundException {
        if (currentFile.isReadOnly()) {
            contentField.setDisable(true);
        } else {
            String front = currentFile.getContent();
            currentFile.setContent(contentField.getText());
            currentFile.setOpen(false);
            if(!fat.judge(currentFile)){
                currentFile.setContent(front);
                currentFile.setOpen(false);
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setContentText("磁盘空间不足");
                alert.show();
                if (currentFile.getParent() == rootFile) {
                    currentFile = rootFile;
                } else {
                    currentFile = currentFile.getParent();
                }
                Stage stage = (Stage) contentField.getScene().getWindow();
                stage.close();
                return;
            }
            fat.applySpace(currentFile);
            currentFile.setOpen(false);
            if (currentFile.getParent() == rootFile) {
                currentFile = rootFile;
            } else {
                currentFile = currentFile.getParent();
            }
            Stage stage = (Stage) contentField.getScene().getWindow();
            stage.close();
            UpdatePieChart.updatePieChart(diskChart);
            writeDisk();
        }
    }

    public static void setDiskChart(PieChart Chart){
        diskChart = Chart;
    }
}
